package org.wangnian.corsprovider.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.Duration;
import java.util.Collections;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOrigins("http://localhost:9091")
//                .allowedMethods("*")
//                .allowedHeaders("*");
//    }
    
    @Bean
    CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许携带凭证，如 cookie
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 设置访问源请求方法
        config.setAllowedMethods(Collections.singletonList("*"));
        // 设置访问源请求头
        config.setAllowedHeaders(Collections.singletonList("*"));
        //有效期 1 h
        config.setMaxAge(Duration.ofHours(1));
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return new CorsFilter(source);
    }
}
